package com.xneure.utils.cipher;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

public class SimpleEncode{
	private static final String DEFAULT_URL_ENCODING = "UTF-8";
	private static final char[] BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();

	/**
	 * Hex编码.
	 */
	public static String encodeHex(byte[] input){
		return new String(Hex.encodeHex(input));
	}

	/**
	 * Hex解码.
	 */
	public static byte[] decodeHex(String input){
		try{
			return Hex.decodeHex(input.toCharArray());
		}catch(DecoderException e){
			throw new RuntimeException(e);
		}
	}

	/**
	 * Base64编码.
	 */
	public static String encodeBase64(byte[] input){
		return new String(Base64.encodeBase64(input));
	}

	/**
	 * Base64解码.
	 */
	public static byte[] decodeBase64(String input){
		return Base64.decodeBase64(input.getBytes());
	}

	/**
	 * Base62编码。
	 */
	public static String encodeBase62(byte[] input){
		char[] chars = new char[input.length];
		for(int i = 0;i < input.length;i++){
			chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
		}
		return new String(chars);
	}

	/**
	 * URL 编码, Encode默认为UTF-8.
	 */
	public static String urlEncode(String part){
		try{
			return URLEncoder.encode(part,DEFAULT_URL_ENCODING);
		}catch(UnsupportedEncodingException e){
			throw new RuntimeException(e);
		}
	}

	/**
	 * URL 解码, Encode默认为UTF-8.
	 */
	public static String urlDecode(String part){
		try{
			return URLDecoder.decode(part,DEFAULT_URL_ENCODING);
		}catch(UnsupportedEncodingException e){
			throw new RuntimeException(e);
		}
	}

	private static String xor(String strOld,String strKey){
		byte[] data = strOld.getBytes();
		byte[] keyData = strKey.getBytes();
		int keyIndex = 0;
		for(int x = 0;x < strOld.length();x++){
			data[x] = (byte)(data[x] ^ keyData[keyIndex]);
			if(++keyIndex == keyData.length){
				keyIndex = 0;
			}
		}
		return new String(data);
	}

	public static String xorEncode(String strOld,String strKey){
		return SimpleEncode.encodeHex(xor(strOld,strKey).getBytes());
	}

	public static String xorDecode(String strOld,String strKey){
		strOld = new String(SimpleEncode.decodeHex(strOld));
		return xor(strOld,strKey);
	}
}
